<template>
    <div class="notice-list" v-loading="loading">
        <common-list @search="search" @resert="resert" @rowClick="rowClick" @rowDblclick="rowDblclick" ref="commonListRef"
            class="common">
            <template #operate="{ scope }">

                <el-button link type="primary" size="small" @click="down(scope)">下载</el-button>
                <div class="line" />
                <el-button link type="primary" size="small" @click="rechristen(scope)">重命名</el-button>
                <div class="line" />
                <el-button link type="primary" size="small" @click="move(scope)">移动</el-button>
                <div class="line" />
                <el-button link type="primary" size="small" @click="deletes(scope)">删除</el-button>
                <div v-if="!scope.scope.row.isFolder" class="line" />
                <el-button v-if="!scope.scope.row.isFolder" link type="primary" size="small"
                    @click="previews(scope)">预览</el-button>

            </template>
            <template #name="{ scope }">
                <div class="flex" v-if="scope.scope.row.isFolder">
                    <img src="@/assets/image/equipmentManagement/iconfolder.png"
                        style="width: 18px; height: 16px; padding-right: 8px" />
                    {{ scope.scope.row.name }}
                </div>
                <div class="flex" v-else>
                    <div v-if="scope.scope.row.suffix == '.docx'">
                        <img src="@/assets/image/equipmentManagement/word.png"
                            style="width: 22px; height: 22px; padding-right: 8px" />
                    </div>
                    <div v-else-if="scope.scope.row.suffix == '.xlsx'">
                        <img src="@/assets/image/equipmentManagement/excel.png"
                            style="width: 22px; height: 22px; padding-right: 8px" />
                    </div>
                    <div v-else-if="scope.scope.row.suffix == '.pdf'">
                        <img src="@/assets/image/equipmentManagement/pdf.png"
                            style="width: 22px; height: 22px; padding-right: 8px" />
                    </div>
                    <div
                        v-else-if="scope.scope.row.suffix == '.JPG' || scope.scope.row.suffix == '.JPEG' || scope.scope.row.suffix == '.PNG' || scope.scope.row.suffix == '.jpg' || scope.scope.row.suffix == '.jpeg' || scope.scope.row.suffix == '.png' || scope.scope.row.suffix == '.gif' || scope.scope.row.suffix == '.GIF'">
                        <img :src="BASE_URL + '/' + scope.scope.row.path"
                            style="width: 22px; height: 22px; padding-right: 8px" />
                    </div>
                    <div v-else>
                        <img src="@/assets/image/equipmentManagement/video.png"
                            style="width: 22px; height: 22px; padding-right: 8px" />
                    </div>
                    {{ scope.scope.row.name }}
                </div>
            </template>
            <template #btns>
                <div class="flex">
                    <text v-if="fileData.length != 0" class="back" @click="back">返回上一级</text><text
                        v-if="fileData.length != 0" class="interval">|</text>
                    <text class="pointer" @click="backAll">全部文件</text>
                    <div v-for="(item, index) in fileData" class="flex">
                        <div class="triangle"></div>
                        <text class="pointer" @click="backIndex(index)">{{ item.name }}</text>
                    </div>
                </div>
                <div class="btns">
                    <el-upload action="#" :http-request="uploadImageContract" :auto-upload="true" :show-file-list="false"
                        accept=".jpg,.jpeg,.png,.gif,.pdf,.PDF,.docx,.xlsx,.mp4,.avi,.mov,.mkv,.flv">
                        <el-button type="primary">新增文件</el-button>
                    </el-upload>
                    <w-button @click="openAddFile">新增文件夹</w-button>
                </div>
            </template>
            <template #anotherWrapper>
                <div class="left-box">
                    <div class="content">
                        <div v-if="!fileType" class="content-box">
                            <text class="content-text">文件详情</text>
                            <div v-if="file == null" class="contnet-image">
                                <img src="@/assets/image/equipmentManagement/folder.png" class="image" />
                                <text class="image-text">选中文件/文件夹，查看详情</text>
                            </div>
                            <div class="content-file" v-else>
                                <div class="files">
                                    <div v-if="file.suffix == '.docx'">
                                        <img src="@/assets/image/equipmentManagement/word.png" class="file-image" />
                                    </div>
                                    <div v-else-if="file.suffix == '.xlsx'">
                                        <img src="@/assets/image/equipmentManagement/excel.png" class="file-image" />
                                    </div>
                                    <div v-else-if="file.suffix == '.pdf'">
                                        <img src="@/assets/image/equipmentManagement/pdf.png" class="file-image" />
                                    </div>
                                    <div
                                        v-else-if="file.suffix == '.JPG' || file.suffix == '.JPEG' || file.suffix == '.PNG' || file.suffix == '.jpg' || file.suffix == '.jpeg' || file.suffix == '.png' || file.suffix == '.gif' || file.suffix == '.GIF'">
                                        <img :src="BASE_URL + '/' + file.path" class="file-image" />
                                    </div>
                                    <div v-else>
                                        <img src="@/assets/image/equipmentManagement/video.png" class="file-image" />
                                    </div>
                                    <text class="file-name">{{ file.name }}</text>
                                </div>
                                <div class="file-line"></div>

                                <div class="file-text">创建时间：{{ file.createTime }}</div>

                                <div class="file-text">最后修改：{{ file.updateTime }}</div>

                                <div class="file-text">文件格式：{{ file.suffix }}</div>

                                <div class="file-text">文件大小：{{ ((file.size / 1024) / 1024).toFixed(2) }}M</div>

                                <div class="file-text" style="display: inline;position:relative; top:16px;">
                                    <text style="float: left;">所在目录</text>
                                    <div>
                                        <div class="flex wrap">
                                            <text class="pointer" style="padding-left:10px;color: #4BA6DD;"
                                                @click="backAll">全部文件</text>
                                            <div v-for="(item, index) in fileData" class="flex">
                                                <div class="triangle"></div>
                                                <text class="pointer" @click="backIndex(index)">{{ item.name }}</text>
                                            </div>
                                        </div>
                                    </div>

                                </div>
                            </div>
                        </div>
                        <div v-else class="content-box">
                            <text class="content-text">文件夹内容</text>
                            <div class="content-file">
                                <div class="files">
                                    <img src="@/assets/image/equipmentManagement/iconfolder.png" class="file-image" />
                                    <text class="file-name">{{ file.name }}</text>
                                </div>
                                <div class="file-line"></div>
                                <div class="scroll" style="height: calc(100% - 60px); overflow: auto">
                                    <p v-for="item in file.childs" class="flex">
                                    <div v-if="item.isFolder"> <img src="@/assets/image/equipmentManagement/iconfolder.png"
                                            style="width: 18px; height: 16px; padding-right: 8px" /></div>
                                    <div v-else>
                                        <div v-if="item.suffix == '.docx'">
                                            <img src="@/assets/image/equipmentManagement/word.png"
                                                style="width: 22px; height: 22px; padding-right: 8px" />
                                        </div>
                                        <div v-else-if="item.suffix == '.xlsx'">
                                            <img src="@/assets/image/equipmentManagement/excel.png"
                                                style="width: 22px; height: 22px; padding-right: 8px" />
                                        </div>
                                        <div v-else-if="item.suffix == '.pdf'">
                                            <img src="@/assets/image/equipmentManagement/pdf.png"
                                                style="width: 22px; height: 22px; padding-right: 8px" />
                                        </div>
                                        <div
                                            v-else-if="item.suffix == '.JPG' || item.suffix == '.JPEG' || item.suffix == '.PNG' || item.suffix == '.jpg' || item.suffix == '.jpeg' || item.suffix == '.png' || item.suffix == '.gif' || item.suffix == '.GIF'">
                                            <img :src="BASE_URL + '/' + item.path"
                                                style="width: 22px; height: 22px; padding-right: 8px" />
                                        </div>
                                        <div v-else>
                                            <img src="@/assets/image/equipmentManagement/video.png"
                                                style="width: 22px; height: 22px; padding-right: 8px" />
                                        </div>
                                    </div>
                                    <div style="font-size: 14px;font-weight: 400;color: #595959;word-break: break-all;">
                                        {{ item.name }}</div>
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </template>
        </common-list>
        <el-dialog destroy-on-close v-model="addFile" title="新增文件夹" :close-on-click-modal="false" width="30%">
            <el-form :model="form" :rules="rule" ref="ruleFormRef">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="文件夹名称" prop="name">
                            <el-input maxlength="30" v-model="form.name" placeholder="请输入文件夹名称" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <div class="button">
                    <div class="submit" @click="submit">
                        <text class="submitText">提交</text>
                    </div>
                    <div class="close" @click="close">
                        <text class="closeText">取消</text>
                    </div>
                </div>
            </el-form>
        </el-dialog>
        <el-dialog destroy-on-close v-model="rechristenFile" title="重命名" :close-on-click-modal="false" width="30%">
            <el-form :model="forms" :rules="file.isFolder ? ruless : rules" ref="ruleFormRefs">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="文件名称" prop="name">
                            <el-input maxlength="30" v-model="forms.name" placeholder="请输入文件名称" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <div class="button">
                    <div class="submit" @click="submits">
                        <text class="submitText">提交</text>
                    </div>
                    <div class="close" @click="closes">
                        <text class="closeText">取消</text>
                    </div>
                </div>
            </el-form>
        </el-dialog>
        <el-dialog destroy-on-close v-model="moveFile" title="移动" :close-on-click-modal="false" width="30%">
            <div>
                <div class="box">
                    <el-tree :data="treeData" :props="defaultProps" :expand-on-click-node="false"
                        @node-click="handleNodeClick" />
                </div>
                <div class="button">
                    <div class="submit" @click="moveSubmit">
                        <text class="submitText">确认</text>
                    </div>
                    <div class="close" @click="moveClose">
                        <text class="closeText">取消</text>
                    </div>
                </div>
            </div>
        </el-dialog>
        <previewPage @previewclose="previewclose" v-if="showTime" :showTime="showTime" :type="type" :name="name"
            :path="path"></previewPage>
    </div>
</template>

<script setup>
import { provide, reactive, ref, computed, watch, nextTick } from "vue";
import { tableConfig, formConfig, getDate } from "./designInformationConfig";
import { getFolderId, getdesigninformationpage, upload, addfile, addfloder, batchdeleteresouce, editresouce, getrelationresourcelist, shiftresourcelocation, downfile, downfolder, getdesigninformationdetailbyid } from "@/service/api/equipmentManagement.js";
import { mainStore } from "@/store/main.js";
import { useRouter } from "vue-router";
import previewPage from "./previewPage.vue"
import wButton from "@/components/wButton.vue";
import { BASE_URL } from "@/service/request/config.js"


const router = useRouter();
const resourceId = computed(() => router.currentRoute.value.query.resourceId);
const commonListRef = ref(null);
const formData = reactive({ id: "", name: "", time: "", startTime: "", endTime: "", });
const file = ref(null);
const fileType = ref(false);
const fileData = ref([])
const addFile = ref(false)
const rechristenFile = ref(false)
const moveFile = ref(false)
const showTime = ref(false)
const form = ref({
    name: "",
});
const forms = ref({
    name: "",
});
const ruleFormRef = ref(null);
const ruleFormRefs = ref(null);
const rule = ref({
    name: [{ required: true, message: "文件夹名称是必填的", trigger: "blur" }]
});
const rules = ref({
    name: [{
        validator: (rule, value, callback) => {
            const first = /^(?=[\u4e00-\u9fa5_a-zA-Z0-9])/;
            const end = /\.(JPG|jpg|JPEG|jpeg|PNG|png|gif|GIF|MP4|mp4|AVI|avi|MOV|mov|MKV|mkv|FLV|flv|docx|xlsx|pdf)$/
            if (!value) {
                callback(new Error("文件名称是必填的"));
            } else if (!first.test(value)) {
                callback(new Error("请以字母、数字或者汉字开头"));
            } else if (!end.test(value)) {
                callback(new Error("请以正确的文件格式结尾"))
            } else {
                return true
            }
        },
        trigger: "blur"
    }]
});
const ruless = ref({
    name: [{ required: true, message: "文件夹名称是必填的", trigger: "blur" }]
})
const treeData = ref()
const defaultProps = ref({
    children: "childs",
    label: "name"
})
const moveId = ref()
const changeMoveId = ref()
const type = ref()
const name = ref()
const path = ref()

if (resourceId.value) {
    formData.id = resourceId.value
    const res = await getdesigninformationdetailbyid({ id: resourceId.value })
    if (res.code === 200) {
        fileData.value = res.data
    }
}


watch(formData, (news) => {
    formData.startTime = news.time[0] ? news.time[0] : "";
    formData.endTime = news.time[1] ? getDate(news.time[1], 1) : "";
});
const openAddFile = () => {
    addFile.value = true
    form.value = {
        name: "",
        id: formData.id
    }
}
const rechristen = (scope) => {
    file.value = scope.scope.row
    rechristenFile.value = true
    forms.value = {
        name: scope.scope.row.name,
        fileId: scope.scope.row.id,
        isFolder: scope.scope.row.isFolder
    }
}
function uploadImageContract(params) {
    console.log(params);
    var file = new FormData();
    // 文件
    file.append("file", params.file);
    const loadingInstance = ElLoading.service();
    getFolderId({ id: formData.id }).then(s => {
        upload(file).then((res) => {
            if (res.code === 200) {
                addfile({
                    id: res.data,
                    parentId: formData.id
                }).then(r => {
                    if (r.code === 200) {
                        ElMessage({
                            type: "success",
                            message: "上传成功"
                        });
                    }
                    commonListRef.value.tableRef.getTableList(res => {
                        fileData.value[fileData.value.length - 1].childs = res
                    });
                    loadingInstance.close();
                }).catch(() => {
                    loadingInstance.close();
                });
            } else {
                ElMessage.error("上传失败");
            }
            commonListRef.value.tableRef.getTableList();
            loadingInstance.close();
        }).catch(() => {
            loadingInstance.close();
        });
    }).catch(() => {
        loadingInstance.close();
    });

}
const back = () => {
    fileData.value.splice(fileData.value.length - 1, 1)
    if (fileData.value.length == 0) {
        formData.id = ""
        file.value = null
        fileType.value = false
    } else {
        formData.id = fileData.value[fileData.value.length - 1].id
        file.value = fileData.value[fileData.value.length - 1]
    }

    commonListRef.value.tableRef.getTableList();

}
const backAll = () => {
    fileData.value = []
    file.value = null
    fileType.value = false
    formData.id = ""
    commonListRef.value.tableRef.getTableList();

}
const backIndex = (index) => {
    fileType.value = true
    fileData.value.splice(index + 1, fileData.value.length - 1 + index)
    file.value = fileData.value[fileData.value.length - 1]
    formData.id = fileData.value[index].id
    commonListRef.value.tableRef.getTableList();

}
const resert = () => {
    Object.keys(formData).forEach((key) => {
        if (key !== "depth" && key !== "storagePath") {
            formData[key] = "";
        }
    });
};
const rowClick = (row, column, event) => {
    file.value = row;
    if (row.isFolder) {
        fileType.value = true;
    } else {
        fileType.value = false;
    }
};
const rowDblclick = (row, column, event) => {
    if (row.isFolder) {
        fileData.value.push(row)
        console.log(fileData.value)
        formData.id = row.id
        commonListRef.value.tableRef.getTableList();
    }

};
const deletes = (scope) => {
    ElMessageBox.confirm("确定删除吗?", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: ""
    }).then(() => {
        const loadingInstance = ElLoading.service();
        batchdeleteresouce({
            ids: scope.scope.row.id
        })
            .then((res) => {
                if (res.code === 200) {
                    ElMessage({
                        type: "success",
                        message: "删除成功"
                    });
                }
                commonListRef.value.tableRef.getTableList(res => {
                    fileData.value[fileData.value.length - 1].childs = res
                });
                fileType.value = false
                file.value = null
                commonListRef.value.tableRef.getTableList();
                loadingInstance.close();
            })
            .catch(() => {
                loadingInstance.close();
            });
    });
};
const submit = () => {
    if (!ruleFormRef.value) return;
    ruleFormRef.value.validate((valid) => {
        if (valid) {
            const loadingInstance = ElLoading.service();

            addfloder(form.value)
                .then((res) => {
                    if (res.code === 200) {
                        ElMessage({
                            message: "添加成功",
                            type: "success"
                        });
                        addFile.value = false;
                    }
                    commonListRef.value.tableRef.getTableList();
                    loadingInstance.close();
                })
                .catch(() => {
                    loadingInstance.close();
                });

        }
    });
}
const close = () => {
    addFile.value = false
}
const submits = () => {
    if (!ruleFormRefs.value) return;
    ruleFormRefs.value.validate((valid) => {
        if (valid) {
            const loadingInstance = ElLoading.service();

            editresouce(forms.value)
                .then((res) => {
                    if (res.code === 200) {
                        ElMessage({
                            message: "修改成功",
                            type: "success"
                        });
                        rechristenFile.value = false;
                    }
                    commonListRef.value.tableRef.getTableList((res) => {
                        file.value = res.find((item) => item.id == file.value.id)
                    });

                    loadingInstance.close();
                })
                .catch(() => {
                    loadingInstance.close();
                });

        }
    });
}
const closes = () => {
    rechristenFile.value = false
}
const move = (scope) => {
    moveId.value = scope.scope.row.id
    moveFile.value = true
    getrelationresourcelist({}).then(res => {
        if (res.code === 200) {
            treeData.value = [{
                childs: res.data, id: "", name: "全部文件"
            }]
        }
    })
}
const moveSubmit = () => {
    if (moveId.value == changeMoveId.value) {
        ElMessage.error("文件不能迁移到当前目录");
    } else {
        const loadingInstance = ElLoading.service();
        shiftresourcelocation({
            id: moveId.value,
            targetId: changeMoveId.value
        }).then(res => {
            if (res.code === 200) {
                ElMessage({
                    message: "迁移成功",
                    type: "success"
                });
                moveFile.value = false;
            }
            fileType.value = false
            file.value = null
            commonListRef.value.tableRef.getTableList();
            loadingInstance.close();
        }).catch(() => {
            loadingInstance.close();
        });
    }

}
const moveClose = () => {
    moveFile.value = false
}
const handleNodeClick = (node) => {
    changeMoveId.value = node.id
}
const down = (scope) => {
    if (scope.scope.row.isFolder) {
        downfolder({ id: scope.scope.row.id }).then((res) => {
            const link = document.createElement("a"); //创建a标签
            let blob = new Blob([res], { type: "application/zip" });
            let objectUrl = URL.createObjectURL(blob);
            link.href = objectUrl;
            link.download = scope.scope.row.name; // 自定义文件名
            link.click(); // 下载文件
            URL.revokeObjectURL(objectUrl);
        });
    } else {
        downfile({ id: scope.scope.row.id }).then((res) => {
            const link = document.createElement("a"); //创建a标签
            let blob = new Blob([res]);
            let objectUrl = URL.createObjectURL(blob);
            console.log(objectUrl)
            link.href = objectUrl;
            link.download = scope.scope.row.name // 自定义文件名
            link.click(); // 下载文件
            URL.revokeObjectURL(objectUrl);
        });
    }
}
const search = () => {
    // formData.Depth = null
    // formData.StoragePath = null
    // fileData.value = []
}
const previews = (scope) => {
    console.log("测试")
    showTime.value = true
    type.value = scope.scope.row.suffix.split('.')[1]
    name.value = scope.scope.row.id
    path.value = scope.scope.row.path
    console.log(path.value)
}
const previewclose = () => {
    showTime.value = false
}
provide("formData", formData);
provide("formConfig", formConfig);
provide("tableConfig", tableConfig);
provide("apiFn", getdesigninformationpage);
// provide("requestBody", "query");
// provide("includeName", ["projectId"]);
// provide("title", "全部文件");
</script>

<style lang="less" scoped>
::v-deep(.el-dialog__title) {
    color: #1b3646;
    font-weight: 600;
}

::v-deep(.el-form-item__label) {
    color: #1b3646;
}

.wrap {
    flex-wrap: wrap;
}

.box {
    height: 200px;
    width: 100%;
    border: 1px solid #BFBFBF;
    overflow: auto;
    margin-bottom: 20px;
}

.triangle {
    width: 0px;
    height: 0px;
    font-size: 0;
    line-height: 0;
    overflow: hidden;
    border-width: 4px;
    border-style: dashed dashed dashed solid;
    border-color: transparent transparent transparent #595959;
    margin: 0 14px;
}

.pointer {
    cursor: pointer;
}

.back {
    font-size: 16px;
    font-weight: 400;
    color: #4BA6DD;
    cursor: pointer;
}

.interval {
    padding: 0 15px;
    color: #EBEBEB;
}

.flex {
    display: flex;
    align-items: center;
}

.file-text {
    font-size: 12px;
    font-weight: 400;
    color: #595959;
    padding-top: 16px;
    display: flex;
}

.file-line {
    height: 1px;
    background: #ebebeb;
}

.files {
    display: flex;
    padding-bottom: 16px;
}

.file-image {
    width: 16px;
    height: 18px;
    padding-right: 12px;
}

.file-name {
    font-size: 16px;
    font-weight: 600;
    color: #1b3646;
    word-break: break-all;
}

.image {
    width: 160px;
    height: 160px;
}

.image-text {
    font-size: 14px;
    font-weight: 400;
    color: #595959;
}

.contnet-image {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%
}

.notice-list {
    height: 100%;

    .common {
        ::v-deep(.wrapper) {
            display: flex;
            padding: 0 0 0 20px;

            .wrapper-left {
                flex: 1;
                width: 1px;
                padding-right: 20px;

                .list-title {
                    .title {
                        display: none;
                    }
                }
            }

            .left-box {
                width: 300px;
                background-color: #ecf1f3;
                display: flex;
                justify-content: flex-end;

                .content {
                    width: 284px;
                    background-color: #fff;

                    .content-box {
                        height: 100%;
                        box-sizing: border-box;
                        padding: 16px;

                        .content-text {
                            font-size: 16px;
                            font-weight: 600;
                            color: #1b3646;
                        }
                    }

                    .content-file {
                        padding: 24px 0 16px;
                        height: 100%;
                        box-sizing: border-box;
                        overflow: auto;
                    }
                }
            }
        }
    }

    .line {
        display: inline-block;
        margin: 0 13px;
        width: 1px;
        height: 8px;
        border: 1px solid #dcdcdc;
    }

    .btns {
        display: flex;

        .resert {
            border: 1px solid @main-color;
            color: @main-color;
        }
    }
}

.scroll::-webkit-scrollbar {
    width: 4px;
}

.scroll::-webkit-scrollbar-thumb {
    border-radius: 10px;
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: rgba(0, 0, 0, 0.2);
}

.scroll::-webkit-scrollbar-track {
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 0;
    background: rgba(0, 0, 0, 0.1);
}

.close {
    margin-left: 8px;
    width: 78px;
    height: 30px;
    border: 1px solid #00428e;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

.closeText {
    color: #00428e;
    font-size: 14px;
    font-weight: 400;
}

.submit {
    width: 80px;
    height: 32px;
    background: #00428e;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
}

.submitText {
    color: #ffffff;
    font-size: 14px;
    font-weight: 400;
}

.button {
    display: flex;
    justify-content: center;
}
</style>
<style>
.el-message-box__btns {
    justify-content: center;
}

.el-message-box__title {
    font-weight: 600;
    color: #1b3646;
}

.el-message-box__message {
    color: #1b3646;
}

.el-message-box__btns .el-button--primary {
    background-color: #00428e;
}
</style>